package agent

import (
	"context"
	"time"

	"github.com/coreos/etcd/clientv3"
	"go.uber.org/zap"
)

// EventMsg report chan message struct
type EventMsg struct {
	Value *clientv3.Event
}

// Etcd etcd struct,report udp listen addr
type Etcd struct {
	Client    *clientv3.Client
	Grant     *clientv3.LeaseGrantResponse
	Addrs     []string
	Dltimeout int
	TTL       int64
	WatchKey  string
	StopC     chan bool
}

// NewEtcd new Etcd
func NewEtcd(Addrs []string, Dltimeout int, TTL int64,
	WatchKey string) *Etcd {

	return &Etcd{
		Addrs:     Addrs,
		Dltimeout: Dltimeout,
		TTL:       TTL,
		WatchKey:  WatchKey,
		StopC:     make(chan bool, 1),
	}
}

// Start start etcd report thread
func (etcd *Etcd) Start() {
	cfg := clientv3.Config{
		Endpoints:   etcd.Addrs,
		DialTimeout: time.Duration(etcd.Dltimeout) * time.Second,
	}

	client, err := clientv3.New(cfg)
	if err != nil {
		Logger.Fatal("etcd", zap.Error(err))
	}
	etcd.Client = client
	go etcd.Watch()
}

// Close stop etcd report
func (etcd *Etcd) Close() {
	etcd.StopC <- true
	time.Sleep(1 * time.Second)
	close(etcd.StopC)
}

// Watch watch
func (etcd *Etcd) Watch() {
	for {
		rch := etcd.Client.Watch(context.Background(), etcd.WatchKey, clientv3.WithPrefix())
		for wresp := range rch {
			for _, ev := range wresp.Events {
				// 上报
				if ev.Type == 0 {
					// log.Println(string(ev.Kv.Key), string(ev.Kv.Value))
					if gAgent.s.isequal(string(ev.Kv.Key), string(ev.Kv.Value)) {
						continue
					}
					gAgent.s.update(string(ev.Kv.Key), string(ev.Kv.Value))
				} else {
					// log.Println(string(ev.Kv.Key))
					gAgent.s.stop()
				}
			}
		}
	}
}

// // GetRegisterKey get key
// func GetRegisterKey() (string, error) {
// 	host, err := os.Hostname()
// 	if err != nil {
// 		return "", err
// 	}
// 	return fmt.Sprintf("%s-%d", host, os.Getpid()), nil
// }
